<template>
  <div class="login-content" :class="bgClass">
    <img v-if="titleImg" class="title-img" :src="titleImg" />

    <div class="login-form-box">
      <el-form ref="form" :model="baseInfo" class="login-form" @keyup.enter.native="subEnterprise()">
        <el-form-item class="login-form-item" prop="identifier">
          <img class="login-form-img" src="../../assets/img/icon_3.png" />
          <el-dropdown trigger="click" placement="bottom-start" :disabled="phoneList.length > 0 ? false : true">
            <el-input v-model="baseInfo.identifier" maxlength="11" name="phone" class="login-item-input" placeholder="手机号码"> </el-input>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in phoneList" :key="item">
                <span @click="setPhone(item)">{{item}}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item class="login-form-item">
          <img class="login-form-img" src="../../assets/img/icon_4.png" />
          <el-input v-model="baseInfo.code" name="code" class="login-item-input" placeholder="6位数验证码"> </el-input>
          <span class="login-form-code" v-if="computeTime == 0" @click="handleGetCode()">获取验证码</span>
          <span class="login-form-time" v-else>{{ computeTime }} s</span>
        </el-form-item>
        <el-button class="login-form-btn" type="primary" @click="subEnterprise()">登录</el-button>
      </el-form>
      <div class="login-form-group">
        <!-- <p style="height: 10px"></p>
        <p @click="registerShow()">账号注册</p> -->
      </div>
    </div>
    <el-dialog class="login-dialog-center" center title="请选择登录企业" :visible.sync="dialogVisible" :close-on-click-modal="false" width="400px" append-to-body>
      <el-select v-model="enterpriseKey" placeholder="请选择">
        <el-option v-for="item in options" :key="item.key" :label="item.enterpriseName" :value="item.key"> </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEvent">确 定</el-button>
      </span>
    </el-dialog>
    <RegisteredUser ref="registeredUser" @onGetCode="handleGetCode" @onChangePassword="handleChangePassword" @onRegister="handleRegister" />
  </div>
</template>

<script>
  import { APPID } from '@/common/js/globalContants';
  import { listUserEnterprise } from '../../api/index';
  import { getLocation } from "@/common/js/utils"
  export default {
    name: 'login',
    data() {
      return {
        computeTime: 0, // 计时的时间

        btnLock: false,

        baseInfo: {
          identifier: '',
          code: '',
          identityType: 'phone',
        },
        options: [],
        dialogVisible: false,
        enterpriseKey: '',
        phoneList: [],
        projectLogo: '',
        bgClass: '',
        titleImg: '',
        systemType: '',
      };
    },

    mixins: [window.yj.basePage],

    created() {
      let systemType = getLocation();
      this.systemType = systemType
      if (systemType == 'assetManagement') {
        // 阳光数字资管
        this.bgClass = 'bg-ziguan'
        this.projectLogo = require('@/common/imgs/ziguan.png')
        this.titleImg = require('../../assets/img/title-ziguan.png')
      } else if (systemType == 'businessBuildingOperate') {
        // 商写运营
        this.bgClass = 'bg-bbOperate'
        this.projectLogo = require('@/common/imgs/ziguan.png')
        this.titleImg = require('../../assets/img/title-bbOperate.png')
      } else {
        // 阳光数字商管
        this.bgClass = 'bg-yunguan'
        this.projectLogo = require('@/common/imgs/yunguan_login.png')
        this.titleImg = require('../../assets/img/title-yunguan.png')
      }
    },

    mounted() {
      localStorage.removeItem('projectKey');
      localStorage.removeItem('token');
      localStorage.removeItem('publicKey');
      localStorage.removeItem('userInfo');
      sessionStorage.removeItem('rootMenuId');
      sessionStorage.removeItem('menuId');
      sessionStorage.removeItem('topNavParams');
      localStorage.removeItem('roleCode');
      localStorage.removeItem('systemType');
      localStorage.removeItem('approveOrderEnterpriseid');
      localStorage.removeItem('userEnterpriseid');
      localStorage.removeItem('APP_MENU_DATA');
      sessionStorage.removeItem("optEnterpriseid");
      let phoneList = localStorage.getItem('phoneList');
      this.phoneList = JSON.parse(phoneList) || [];
    },

    methods: {
      handleGetCode(phone) {
        let tel = phone || this.baseInfo.identifier;
        window.yj
          .getSmsCode(tel)
          .then(data => {
            if (phone) {
              return;
            }
            // 启动倒计时
            this.computeTime = window.yj.constants.CODE_INTERVAL_SECONDS;
            this.intervalId = setInterval(() => {
              this.computeTime -= 1;
              if (this.computeTime <= 0) {
                // 停止计时
                clearInterval(this.intervalId);
              }
            }, 1000);
          })
          .catch(error => {
            error.message && this.$message.error(error.message);
          });
      },

      registerShow() {
        this.$refs.registeredUser.showRegisterDialog();
      },

      handleRegister(registerForm) {
        window.yj
          .register(registerForm.phone, registerForm.password, registerForm.code)
          .then(res => {
            this.$message.success(res.message);
            this.$refs['registeredUser'].close();
          })
          .catch(error => {
            error.message && this.$message.error(error.message);
          });
      },

      handleChangePassword(registerForm) {
        window.yj
          .updatePasswordBySmsCode(registerForm.password, registerForm.code)
          .then(res => {
            this.$message.success(res.message);
            this.$refs['registeredUser'].close();
          })
          .catch(error => {
            error.message && this.$message.error(error.message);
          });
      },
      async subEnterprise() {
        this.enterpriseKey = '';
        const listRes = await listUserEnterprise({ phone: this.baseInfo.identifier, appid: APPID });
        if (listRes.rows && listRes.rows.length > 1) {
          this.options = listRes.rows;
          this.dialogVisible = true;
        } else if (listRes.rows && listRes.rows.length === 1) {
          localStorage.setItem('userEnterpriseid', listRes.rows[0].key);
          this.onSubmit(listRes.rows[0].key);
        } else {
          this.$message.error('该账号暂无企业！');
        }
      },
      submitEvent() {
        localStorage.setItem('userEnterpriseid', this.enterpriseKey);
        this.onSubmit(this.enterpriseKey);
      },
      onSubmit(enterpriseid) {
        window.yj
          .loginBySms(this.baseInfo.identifier, this.baseInfo.code, enterpriseid, APPID)
          .then(async res => {
            localStorage.setItem('systemType', this.systemType);
            this.$message.success(res.message);
            localStorage.setItem('roleCode', JSON.stringify(res.data.extend.roleCode));
            await window.yj.authority.init();
            this.addPhone(); //添加历史记录phone
            if (this.$route.query.redirectUrl) {
              location.replace(decodeURIComponent(this.$route.query.redirectUrl));
            } else {
              location.replace('/pcIndex/');
            }
          })
          .catch(error => {
            error.data.message && this.$message.error(error.data.message);
            if (this.computeTime > 0) {
              // 停止计时
              clearInterval(this.intervalId);
              this.computeTime = 0;
            }
          });
      },
      addPhone() {
        if (this.phoneList.indexOf(this.baseInfo.identifier) < 0) {
          this.phoneList.push(this.baseInfo.identifier);
        }
        let phoneList = JSON.stringify(this.phoneList)
        localStorage.setItem("phoneList",phoneList)
      },
      setPhone(phone) {
        console.log(phone)
        this.baseInfo.identifier = phone;
      },
    },
  };
</script>

<style lang="scss">
  .bg-yunguan {
    background-image: url('../../assets/img/bg-yunguan.png');
  }

  .bg-ziguan {
    background-image: url('../../assets/img/bg-ziguan.png');
  }

  .bg-bbOperate {
    background-image: url('../../assets/img/bg-bbOperate.png');
  }

  .login-content {
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    min-width: 600px;
    min-height: 700px;
    background-size: cover;

    .title-img {
      position: absolute;
      left: 10%;
      top: 10%;
      height: 90px;
    }

    .login-form-box {
      position: fixed;
      right: 5%;
      top: 50%;
      -webkit-transform: translateY(-50%);
      -moz-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
      -o-transform: translateY(-50%);
      transform: translateY(-50%);
    }

    .login-form-group {
      padding: 20px 0px;
      display: flex;
      height: 28px;
      font-size: 16px;
      font-weight: 500;
      color: #ffffff;
      line-height: 28px;
      p {
        flex: 1;
        text-align: center;
        cursor: pointer;
      }
      span {
        padding: 0 20px;
        cursor: pointer;
      }
    }

    .login-form {
      width: 18vw;
      min-width: 300px;
      padding: 22px 2.1vw;
      background: rgba(255, 255, 255, 1);
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
      .login-form-btn {
        width: 100%;
      }
      .login-form-item {
        .el-form-item__content {
          border-bottom: 1px solid #cccccc;
          display: flex;
          align-items: center;
        }
        .login-form-img {
          width: 21px;
          height: 21px;
        }
        .login-item-input {
          flex: 1;
          .el-input__inner {
            height: 20px;
            line-height: 20px;
            border: 0px;
            color: #000000;
            font-size: 16px;
          }
        }
        .login-form-code {
          font-size: 14px;
          height: 20px;
          line-height: 20px;
          font-size: 14px;
          font-weight: 400;
          color: #409eff;
          cursor: pointer;
        }
        .login-form-time {
          color: #606266;
          cursor: default;
          padding: 0 20px;
          pointer-events: none;
        }
      }
    }
  }
  .ban-click {
    pointer-events: none;
    background: #ccc;
    border-color: #ccc;
  }
  .login-dialog-center {
    .el-select {
      padding: 30px 0;
      width: 100%;
    }
  }
</style>
